package com.gxar.quick.ar.server.db.service;

import com.github.pagehelper.PageHelper;
import com.gxar.common.entity.SlippageResult;
import com.gxar.common.entity.SystemCodeEnum;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.utils.AssertUtils;
import com.gxar.common.utils.SnowFlakeUtils;
import com.gxar.fusion.redis.service.RedisService;
import com.gxar.quick.ar.server.base.common.constant.RedisConstant;
import com.gxar.quick.ar.server.base.common.constant.WorksConstant;
import com.gxar.quick.ar.server.base.common.enums.order.OrderStatusEnum;
import com.gxar.quick.ar.server.base.model.order.mapper.OrderMapStruct;
import com.gxar.quick.ar.server.base.model.order.vo.request.OrderCreateRequest;
import com.gxar.quick.ar.server.base.model.order.vo.response.OrderListResponse;
import com.gxar.quick.ar.server.db.mapper.OrderMapper;
import com.gxar.quick.ar.server.db.mapper.OrderProductMapper;
import com.gxar.quick.ar.server.db.model.OrderEntity;
import com.gxar.quick.ar.server.db.model.OrderProductEntity;
import com.gxar.quick.ar.server.db.repository.OrderProductRepository;
import com.gxar.quick.ar.server.db.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2023/11/6 17:58
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {

    private final RedisService redisService;
    private final OrderMapper orderMapper;
    private final OrderProductMapper orderProductMapper;
    private final OrderProductRepository orderProductRepository;
    private final OrderRepository orderRepository;

    /**
     * 订单列表请求
     *
     * @param userProfile 用户信息
     * @param nextId      下一个ID
     * @return 响应
     */
    public SlippageResult<OrderListResponse> list(UserProfile userProfile, String nextId) {
        int pageNumber = 1;
        if (StringUtils.isNotBlank(nextId)) {
            String pageKey = String.format(RedisConstant.ORDER_PAGE_KEY, userProfile.getId(), nextId);
            Object pageInfo = redisService.get(pageKey);
            if (pageInfo != null) {
                pageNumber = Integer.parseInt(pageInfo.toString());
                redisService.remove(pageKey);
            }
        }
        PageHelper.startPage(pageNumber, WorksConstant.DEFAULT_QUERY_LIMIT);
        List<OrderEntity> orderEntities = orderMapper.queryPage(userProfile.getId(), OrderStatusEnum.PAID.getCode());
        if (CollectionUtils.isEmpty(orderEntities)) {
            return SlippageResult.build(null, Collections.emptyList());
        }
        List<OrderListResponse> orderListResponses = OrderMapStruct.INSTANCE.entityToListResponses(orderEntities);
        List<String> orderIdList = orderListResponses.stream().map(OrderListResponse::getId)
                .collect(Collectors.toList());
        List<OrderProductEntity> orderProductList = orderProductMapper.findByOrderId(orderIdList);
        Map<Long, List<OrderProductEntity>> orderProductMap = Optional.of(orderProductList)
                .orElse(Collections.emptyList()).stream()
                .collect(Collectors.groupingBy(OrderProductEntity::getOrderId));
        for (OrderListResponse response : orderListResponses) {
            List<OrderProductEntity> orderProductEntities = orderProductMap.get(Long.parseLong(response.getId()));
            if (CollectionUtils.isNotEmpty(orderProductEntities)) {
                // 第一期一个订单只有一个产品
                if (orderProductEntities.size() == 1) {
                    OrderProductEntity orderProductEntity = orderProductEntities.get(0);
                    response.setStartTime(orderProductEntity.getStartTime());
                    response.setEndTime(orderProductEntity.getEndTime());
                    response.setProductId(orderProductEntity.getProductId() != null ? String.valueOf(orderProductEntity.getProductId()) : null);
                    response.setProductType(orderProductEntity.getType());
                    response.setProductConfig(orderProductEntity.getConfigInfo());
                }
            }
        }
        String nextedId = SnowFlakeUtils.getInstance().nextId();
        String pageKey = String.format(RedisConstant.ORDER_PAGE_KEY, userProfile.getId(), nextedId);
        redisService.set(pageKey, pageNumber + 1);
        redisService.expire(pageKey, RedisConstant.DEFAULT_EXPIRE_SECONDS);
        return SlippageResult.build(nextedId, orderListResponses);
    }

    /**
     * 订单创建
     *
     * @param userProfile        用户配置
     * @param orderCreateRequest 请求
     * @return 响应
     */
    public OrderEntity create(UserProfile userProfile, OrderCreateRequest orderCreateRequest) {
        OrderEntity order = new OrderEntity();
        String orderId = SnowFlakeUtils.getInstance().nextId();
        order.setId(Long.valueOf(orderId));
        order.setStatus(OrderStatusEnum.UN_PAY.getCode());
        order.setMethod(orderCreateRequest.getMethod());
        order.setOriPrice(orderCreateRequest.getOriPrice());
        //暂时无优惠信息
        order.setActualPrice(orderCreateRequest.getPrice());
        order.setUserId(userProfile.getId());
        order.setCreatedAt(new Date());
        order.setUpdatedAt(order.getCreatedAt());
        order.setCreator(userProfile.getMobile());
        order.setOperator(userProfile.getMobile());
        return orderRepository.save(order);
    }

    public void updateOrderStatus(OrderEntity order, OrderStatusEnum orderStatusEnum) {
        order.setStatus(orderStatusEnum.getCode());
        order.setUpdatedAt(new Date());
        orderRepository.save(order);
    }

    public void updateOrderStatusById(Long orderId, OrderStatusEnum orderStatusEnum) {
        Optional<OrderEntity> orderOption = orderRepository.findById(orderId);
        if (orderOption.isPresent()) {
            OrderEntity order = orderOption.get();
            order.setStatus(orderStatusEnum.getCode());
            order.setUpdatedAt(new Date());
            orderRepository.save(order);
        }
    }

    public void createOrderProduct(UserProfile userProfile, OrderProductEntity orderProductEntity) {
        AssertUtils.notNull(orderProductEntity, SystemCodeEnum.SERVER_ERROR.getRet(), "订单产品信息不能为空");
        AssertUtils.notNull(orderProductEntity.getOrderId(), SystemCodeEnum.SERVER_ERROR.getRet(), "订单id不能为空");
        AssertUtils.notNull(orderProductEntity.getProductId(), SystemCodeEnum.SERVER_ERROR.getRet(),
                "订单产品id不能为空");
        orderProductEntity.setCreatedAt(new Date());
        orderProductEntity.setUpdatedAt(orderProductEntity.getCreatedAt());
        orderProductEntity.setCreator(userProfile.getMobile());
        orderProductEntity.setOperator(userProfile.getMobile());
        orderProductRepository.save(orderProductEntity);
    }
}
